package com.woniu.shop.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Configuration
public class AliyunUploadUtils {
    @Value("${aLiYun.accessKey}")
    private String accessKey;
    @Value("${aLiYun.secretKey}")
    private String secretKey;
    @Value("${aLiYun.bucket}")
    private String bucket;
    @Value("${aLiYun.endpoint}")
    private String endpoint;

    private static String ACCESSKEY;
    private static String SECRETKEY;
    private static String BUCKET;
    private static String ENDPOINT;

    // 对象创建之后执行该方法
    @PostConstruct
    public void init(){
        ACCESSKEY = this.accessKey;
        SECRETKEY = this.secretKey;
        BUCKET = this.bucket;
        ENDPOINT = this.endpoint;
    }
    public static String uploadOneFile(MultipartFile file,String fileName) throws IOException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEY, SECRETKEY);
        // meta设置请求头
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType("image/jpg");
        try {
            // 创建PutObject请求。
            ossClient.putObject(BUCKET, fileName, file.getInputStream(),meta);

            String url = "http://" + BUCKET + "." + ENDPOINT + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static boolean deleteFile(String fileUrl) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEY, SECRETKEY);
        /** oss删除文件是根据文件完成路径删除的，但文件完整路径中不能包含Bucket名称。
         * 比如文件路径为：http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
         * 则完整路径就是：2022/08/abc.jpg
         */
//        int begin = ("http://" + BUCKET + "." + ENDPOINT + "/").length(); //找到文件路径的开始下标
//        String deleteUrl = fileUrl.substring(begin-1);

        try {
            // 删除文件请求
            ossClient.deleteObject(BUCKET, fileUrl);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
